﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Collections.Generic;
using System.Web;

namespace Skupine_Web_Part.SkupineWP
{
    [ToolboxItem(false)]
    public partial class SkupineWP : WebPart, IWebEditable
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }
        public string username { get; set; }
        public string password { get; set; }
        public string ldapQuery { get; set; }
        public string DCName { get; set; }




        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                if (!ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
                {
                    DirectoryEntry ldapConn = new DirectoryEntry(DCName);
                    ldapConn.Path = "LDAP://" + ldapQuery;
                    ldapConn.Username = username;
                    ldapConn.Password = password;
                    ldapConn.AuthenticationType = AuthenticationTypes.Secure;



                    SPWeb web = SPContext.Current.Web;
                    SPSite site = SPContext.Current.Site;
                    string siteUrl = site.Url;
                    SPList userList = site.RootWeb.SiteUserInfoList;
                    Guid userListID = userList.ID;

                    SPGroupCollection groups = web.Groups;

                    foreach (SPGroup group in groups)
                    {

                        TreeNode skupineTreeNode = new TreeNode(group.Name);
                        skupineTreeNode.ImageUrl = siteUrl + @"/_layouts/images/skupine%20web%20part/group.png";

                        TreeView1.Nodes.Add(skupineTreeNode);
                        if (group.OnlyAllowMembersViewMembership == false || group.CanCurrentUserViewMembership == true)
                        {
                            skupineTreeNode.NavigateUrl = web.Url + @"/_layouts/userdisp.aspx?id=" + group.ID;

                            try
                            {
                                foreach (SPUser user in group.Users)
                                {
                                    TreeNode uporabnikiSkupine = new TreeNode(user.Name);
                                    uporabnikiSkupine.NavigateUrl = siteUrl + @"/_layouts/listform.aspx?PageType=4&ListId=" + userListID + @"&ID=" + user.ID;
                                    uporabnikiSkupine.ImageUrl = siteUrl + @"/_layouts/images/skupine%20web%20part/user.png";
                                    skupineTreeNode.ChildNodes.Add(uporabnikiSkupine);
                                    if (user.IsDomainGroup)
                                    {
                                        uporabnikiSkupine.ImageUrl = siteUrl + @"/_layouts/images/skupine%20web%20part/Domaingroup.png";

                                        try
                                        {

                                            string cnName = user.Name.Substring(user.Name.IndexOf(@"\") + 1);
                                            DirectorySearcher search = new DirectorySearcher(ldapConn);
                                            search.Filter = "(cn=" + cnName + ")";
                                            search.PropertiesToLoad.Add("member");



                                            SearchResult result = search.FindOne();
                                            if (result != null)
                                            {
                                                ResultPropertyCollection fields = result.Properties;

                                                try
                                                {

                                                    foreach (Object myColl in fields["member"])
                                                    {
                                                        string clanSkupine = myColl.ToString().Substring(myColl.ToString().IndexOf("=") + 1, myColl.ToString().IndexOf(",") - myColl.ToString().IndexOf("=") - 1);
                                                        TreeNode claniSkupin = new TreeNode(clanSkupine);
                                                        claniSkupin.ImageUrl = siteUrl + @"/_layouts/images/skupine%20web%20part/user.png";
                                                        uporabnikiSkupine.ChildNodes.Add(claniSkupin);

                                                        DirectorySearcher searchUser = new DirectorySearcher(ldapConn);
                                                        searchUser.Filter = "(cn=" + clanSkupine + ")";
                                                        searchUser.PropertiesToLoad.Add("mail");
                                                        SearchResult userResult = searchUser.FindOne();
                                                        string userMail = "";
                                                        if (userResult != null)
                                                        {
                                                            ResultPropertyCollection userFields = userResult.Properties;
                                                            try
                                                            {
                                                                userMail = userResult.Properties["mail"][0].ToString();

                                                            }
                                                            catch (Exception)
                                                            {

                                                                throw;
                                                            }
                                                        }

                                                        SPUserCollection us = web.AllUsers;
                                                        try
                                                        {
                                                            SPUser domainUser = web.AllUsers.GetByEmail(userMail);

                                                            claniSkupin.NavigateUrl = siteUrl + @"/_layouts/listform.aspx?PageType=4&ListId=" + userListID + @"&ID=" + domainUser.ID;

                                                        }

                                                        catch { }

                                                    }
                                                }
                                                catch { }
                                            }
                                        }
                                        catch { }
                                    }
                                }
                            }
                            catch { }
                        }
                        else { }
                    }

                    SPUserCollection users = web.Users;
                    foreach (SPUser user in users)
                    {
                        TreeNode uporabnikiTreeNode = new TreeNode(user.Name);
                        uporabnikiTreeNode.NavigateUrl = siteUrl + @"/_layouts/listform.aspx?PageType=4&ListId=" + userListID + @"&ID=" + user.ID;
                        uporabnikiTreeNode.ImageUrl = siteUrl + @"/_layouts/images/skupine%20web%20part/user.png";
                        TreeView1.Nodes.Add(uporabnikiTreeNode);

                        if (user.IsDomainGroup)
                        {
                            uporabnikiTreeNode.ImageUrl = siteUrl + @"/_layouts/images/skupine%20web%20part/Domaingroup.png";

                            try
                            {
                                string cnName = user.Name.Substring(user.Name.IndexOf(@"\") + 1);
                                DirectorySearcher search = new DirectorySearcher(ldapConn);
                                search.Filter = "(cn=" + cnName + ")";
                                search.PropertiesToLoad.Add("member");


                                SearchResult result = search.FindOne();


                                if (result != null)
                                {
                                    ResultPropertyCollection fields = result.Properties;

                                    try
                                    {
                                        foreach (Object myColl in fields["member"])
                                        {
                                            string clanSkupine = myColl.ToString().Substring(myColl.ToString().IndexOf("=") + 1, myColl.ToString().IndexOf(",") - myColl.ToString().IndexOf("=") - 1);
                                            TreeNode claniSkupin = new TreeNode(clanSkupine);
                                            claniSkupin.ImageUrl = siteUrl + @"/_layouts/images/skupine%20web%20part/user.png";
                                            uporabnikiTreeNode.ChildNodes.Add(claniSkupin);

                                            DirectorySearcher searchUser = new DirectorySearcher(ldapConn);
                                            searchUser.Filter = "(cn=" + clanSkupine + ")";
                                            searchUser.PropertiesToLoad.Add("mail");
                                            SearchResult userResult = searchUser.FindOne();
                                            string userMail = "";
                                            if (userResult != null)
                                            {
                                                ResultPropertyCollection userFields = userResult.Properties;
                                                try
                                                {
                                                    userMail = userResult.Properties["mail"][0].ToString();

                                                }
                                                catch (Exception)
                                                {

                                                    throw;
                                                }
                                            }

                                            SPUserCollection us = web.AllUsers;
                                            try
                                            {
                                                SPUser domainUser = web.AllUsers.GetByEmail(userMail);

                                                claniSkupin.NavigateUrl = siteUrl + @"/_layouts/listform.aspx?PageType=4&ListId=" + userListID + @"&ID=" + domainUser.ID;

                                            }

                                            catch { }

                                        }
                                    }
                                    catch { }
                                }
                            }
                            catch (Exception ex)
                            {
                                string exc = ex.Message;
                            }
                        }
                    }
                    web.Dispose();
                }
            }
        }

        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();
            SkupineEditor editorPart = new SkupineEditor();
            editorPart.ID = this.ID + "_editorPart";
            editors.Add(editorPart);
            return new EditorPartCollection(editors);
        }

        object IWebEditable.WebBrowsableObject
        {
            get
            {
                return this;
            }
        }
    }


}
